# -*- coding: utf-8 -*-

import json
import urllib2
import urllib

from kivy.logger import Logger

from constants import JSON_TIMEOUT

from model.gamestate import *


class JsonLoader():
    def dump_to_url(self, url, all_json):
        try:
            urllib2.urlopen(url, urllib.urlencode(
                [('json', json.dumps(all_json,
                                     encoding='utf-8',
                                     sort_keys=True))]), timeout=JSON_TIMEOUT)
        except urllib2.URLError as error:
            Logger.debug('dump_to_url(): connection problem')
            pass

    def load_from_url(self, url):
        Logger.debug('load_from_url(): connecting to %s' % url)
        Logger.debug('load_from_url(): with timeout %d' % JSON_TIMEOUT)
        file_opened = urllib2.urlopen(url, timeout=JSON_TIMEOUT)
        # ToDo : should we close this file?
        return json.loads(file_opened.read())

    def load_game_from_url(self, url):
        file = self.json_translate(self.load_from_url(url))
        return file

    def json_translate(self, json_data):
        self.data = json_data
        self.game_state = GameState(None, None, None, None, None, None, None)
        self.game_state.players = Players([])
        for pos in range(len(self.data[u'players'])):
            self.game_state.players.add(Player(self.data[u'players'][pos], []))

        self.game_state.hat = Hat([])
        for pos in range(len(self.data[u'hat'])):
            owner_num = self.data[u'hat'][pos][u'owner']
            if owner_num is None:
                owner = None
            else:
                owner = self.game_state.players.players[owner_num]
            word_text = self.data[u'hat'][pos][u'text']
            word = Word(owner, word_text)

            self.game_state.hat.add_word(word)
            if owner_num is not None:
                self.game_state.players.players[owner_num].add_word(word)

        if (len(self.data[u'players']) % 2 == 0):
            self.game_state.players.set_next_pair_strategy(
                TraditionalStrategy(self.game_state.players.players))
        else:
            self.game_state.players.set_next_pair_strategy(
                OddStrategy(self.game_state.players.players))

        if u'remote_id' in self.data:
            self.game_state.remote_id = self.data[u'remote_id']

        self.game_state.settings = Settings()
        if u'settings' in self.data:
            self.load_settings()

        return self.game_state

    def load_settings(self):
        self.game_state.settings.time_per_round_sec = \
            self.data[u'settings'][u'time_per_round_sec']

        self.game_state.settings.time_before_out_sec = \
            self.data[u'settings'][u'time_before_out_sec']

        self.game_state.settings.skip_words = \
            self.data[u'settings'][u'skip_words_per_round']
